/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.front.web.pay.wx;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thinkgem.jeesite.common.utils.CommonParameter;
import com.thinkgem.jeesite.common.utils.wx.QRCODETool;
import com.thinkgem.jeesite.common.utils.wx.RandomStringGenerator;
import com.thinkgem.jeesite.common.utils.wx.WeixinSign;
import com.thinkgem.jeesite.common.utils.wx.WeixinXmlTool;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.accountinfo.entity.AccountInfo;
import com.thinkgem.jeesite.modules.config.entity.weixin.ConfigWechat;
import com.thinkgem.jeesite.modules.config.service.weixin.ConfigWechatService;
import com.thinkgem.jeesite.modules.pay.service.log.EcPayLogService;
import com.thinkgem.jeesite.modules.shop.entity.info.ShopOrderInfo;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;

/**
 * 支付Controller（FRONT）
 * 
 * @author Egan
 * @version 2016-12-15
 */
@Controller
@RequestMapping(value = "${frontPath}/pay/wx")
public class WXPayController extends BaseController {
	private static Log log = LogFactory.getLog(WXPayController.class);
	
	@Autowired EcPayLogService ecPayLogService;
	
	@Autowired ShopOrderService shopOrderService;
	
	@Autowired WXPayService wxPayService;
	
	@Autowired
    ConfigWechatService configWechatService;
	
	@RequestMapping(value = "forPay")
	@ResponseBody
	public Object forPay(HttpServletRequest req, HttpServletResponse resp,String coNum, String txnAmt,Model model) {
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			if (log.isDebugEnabled()) {
				log.debug("coNum:" + coNum + ",txnAmt:" + txnAmt);
			}
			ConfigWechat configWechat = configWechatService.getConfigWechat();
			ShopOrder order = shopOrderService.findByCoNum(coNum);
			List<ShopOrderInfo> infos = order.getShopOrderInfoList();
			Map<String,String> urlMap = wxPayService.forPay(txnAmt,coNum,configWechat,req,infos);
			
			if (log.isDebugEnabled()) {
				log.debug("urlMap:" + urlMap.toString());
			}
			if ("success".equals(urlMap.get("flag"))) {
	            String url = urlMap.get("url");
	            String picName= QRCODETool.getQrCodePic(req,url);
	            resultMap.put("path", CommonParameter.uploadPath);
	            resultMap.put("picName", picName);
	            resultMap.put("msg", urlMap.get("flag"));
	        } else {
	        	resultMap.put("msg", urlMap.get("msg"));
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	@RequestMapping(value = "forResult")
	public void forResult(HttpServletRequest request, HttpServletResponse resp, Model model) {
		try {
			String message = recieveData(request);
			if (log.isDebugEnabled()) {
				log.debug("message:" + message);
			}
			ConfigWechat configWechat = configWechatService.getConfigWechat();
			
			String result = wxPayService.forResult(message,configWechat);
			if (log.isDebugEnabled()) {
				log.debug("result:" + result);
			}
			model.addAttribute("result", result);
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "forCheck")
	@ResponseBody
	public Object forCheck(HttpServletRequest req, HttpServletResponse resp, Model model) {
		String orderId = req.getParameter("orderId");
		Map<String,Boolean> resultMap = new HashMap<String,Boolean>();
		try {
			ConfigWechat configWechat = configWechatService.getConfigWechat();
			resultMap = wxPayService.checkPayResult(orderId,configWechat);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return resultMap;
	}
	
	//接收请求发来的xml消息体
	public static String recieveData(HttpServletRequest request) {
		String inputLine = null;
		// 接收到的数据
		StringBuffer recieveData = new StringBuffer();
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			while ((inputLine = in.readLine()) != null) {
				recieveData.append(inputLine);
			}
			in.close();
		} catch (IOException e) { }finally {            
            try {
                if (null != in) {
                	in.close();
                }
            } catch (IOException e){}            
        }
		return recieveData.toString();
	}
	
	@RequestMapping(value = "forMech")
	@ResponseBody
	public Object forMech(String txnAmt,String coNum,HttpServletRequest req,HttpSession session) {
		try {
			ConfigWechat configWechat = configWechatService.getConfigWechat();
			
			Object user = session.getAttribute("user");
			String openId = ((AccountInfo)user).getWechatNum();
			Map<String, String> paramMap = wxPayService.getSignMapGZ(txnAmt,coNum,openId,configWechat,req);
			// 生成签名
			String sign = WeixinSign.getWeixinPaySignGZ(paramMap);
			paramMap.put("sign", sign);
			// 生成请求xml报文
	        String xmlStr = WeixinXmlTool.getWeixinPayXmlGZ(paramMap);
	        String result = WeixinXmlTool.sendPost(configWechat.getPayUrl(), xmlStr);
	        
	        log.debug("result:" + result);
	        Map<String, String[]> resultMapForOrder = WeixinXmlTool.getPayResultFromXml(result);
			String prepay_id = resultMapForOrder.get("prepay_id")[0];
			
			Map<String,String> resultMap = new HashMap<String, String>();
			String timeStamp = RandomStringGenerator.getDay();
			resultMap.put("appId", configWechat.getAppIdGz());
			resultMap.put("appKey", configWechat.getAppKey());
			resultMap.put("timeStamp", timeStamp);
			resultMap.put("nonceStr", RandomStringGenerator.getRandomStringByLength(32));
			resultMap.put("signType", "MD5");
			resultMap.put("package2", "prepay_id=" + prepay_id);
			String signGZ = WeixinSign.getGZSign(resultMap);
			resultMap.put("paySign", signGZ);
	        return resultMap;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
}